package com.WaVel.task;

import com.Emplyment.entity.Article;
import com.Emplyment.entity.QuestionBank;
import com.Emplyment.util.CacheHotCompany;
import com.WaVel.service.TaskService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CompanyTask {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String COMPANY_HOT_DATA = "company:ZSET:rank";

    private static final String INTERVIEW_HOT_DATA = "interview:ZSET:rank";

//    @Scheduled(cron = "0 0 */2 * * ?")
    @XxlJob("computeHotCompanyJob")
    public void processCompanyData() {
        log.info("将公司热点数据写入缓存中...");
        if(Boolean.TRUE.equals(redisTemplate.hasKey(COMPANY_HOT_DATA))){
            redisTemplate.delete(COMPANY_HOT_DATA);
        }
        try {
            List<Article> list = taskService.getHotCompany();
            for (Article article : list) {
                //todo:基于线程池添加
                String id = article.getId().toString();
                log.info("正在写入缓存：{}",id);
                //删除旧缓存
                if (article.getCollectNumber() == null){
                    article.setCollectNumber(0);
                }
                redisTemplate.opsForZSet().add(COMPANY_HOT_DATA,id,article.getCollectNumber());
            }

        }catch (Exception e){
            log.error("热门数据写入缓存失败：{}",e);
        }
    }

    /**
     * 将面试问题Top100写入缓存当中
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void processInterviewData() {
        log.info("将面试问题Top100写入缓存中...");
        if(Boolean.TRUE.equals(redisTemplate.hasKey(INTERVIEW_HOT_DATA))){
            redisTemplate.delete(INTERVIEW_HOT_DATA);
        }
        try {
            List<QuestionBank> list = taskService.getHotInterview();
            for (QuestionBank questionBank : list) {
                //todo:基于线程池添加
                String id = questionBank.getId().toString();
                //删除旧缓存
                if (questionBank.getCollectNum() == null){
                    questionBank.setCollectNum(0);
                }
                redisTemplate.opsForZSet().add(INTERVIEW_HOT_DATA,id,questionBank.getCollectNum());
            }
        }catch (Exception e){
            log.error("热门面试问题数据写入缓存失败：{}",e);
        }
    }
}
